package com.thread.auxiliaryClassUse;

import java.util.List;
import java.util.Set;
import java.util.concurrent.*;

/**
 * 可以用于多线程计算数据，最后合并计算结果的场景。
 * 模拟计算3个同学的评价成绩
 */
public class CyclicBarrierTest02 {

    ExecutorService executorService = Executors.newFixedThreadPool(10);

    private ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<String, Integer>();

    // 计算3个同学的评价成绩
    CyclicBarrier cyclicBarrier = new CyclicBarrier(3, new Runnable() {
        @Override
        public void run() {
            int result = 0;
            Set<String> set= map.keySet();
            for (String key: set) {
                result+=map.get(key);
            }
            System.out.println("三人平均成绩为:"+(result/3)+"分");
        }
    });

    // 计算每个同学的评价成绩
    public void count(){
        for (int i = 0; i < 3; i++) {
           executorService.execute(new Runnable() {
               @Override
               public void run() {
                   int score = (int) (Math.random()*40+60);
                   map.put(Thread.currentThread().getName(),score);
                   System.out.println(Thread.currentThread().getName()
                           +"同学的平均成绩为："+score);
                   //执行完运行await(),等待所有学生平均成绩都计算完毕
                   try {
                       cyclicBarrier.await();
                   } catch (InterruptedException e) {
                       e.printStackTrace();
                   } catch (BrokenBarrierException e) {
                       e.printStackTrace();
                   }
               }
           });
        }
    }

    public static void main(String[] args) {
        CyclicBarrierTest02 cyclicBarrierTest02 = new CyclicBarrierTest02();
        cyclicBarrierTest02.count();
    }

}